/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import com.mysql.jdbc.Connection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Pavilion
 */
@WebServlet(name = "ServletRegistrar", urlPatterns = {"/ServletRegistrar"})
public class ServletRegistrar extends HttpServlet {
   static String login = "root";
   static String password = "santiago";
   private String nombre=null;
   private String apellido = null;
   private String usuario = null;
   private String clave = null;
   Connection connect = null;
      
   public void init(ServletConfig config) throws ServletException {
       super.init(config);
       String url = new String("jdbc:mysql://localhost/usuario");       
       try{
         Class.forName("com.mysql.jdbc.Driver");           
       }catch(ClassNotFoundException e){
           System.out.println("Error al cargar el driver");
           System.out.println(e.getMessage());
       }try{
           connect = (Connection) DriverManager.getConnection(url,login,password);              
       }catch(SQLException sqlEx){
           System.out.println("Se ha producido un error al"+"establecer la conexion con: "+url);
           System.out.println(sqlEx.getMessage());
       }
       System.out.println("Iniciando Servlet ....");
   }
   
    public void destroy(){
        super.destroy();
        System.out.println("Cerrando conexion...");
        try {
            connect.close();
        }catch(SQLException e){
            System.out.println("No se pudo cerrar la conexion");
            System.out.println(e.getMessage());
        }
            
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            int status = InsertarUsuario(request.getParameter("apellido"),request.getParameter("nombre"),request.getParameter("tipodoc"),request.getParameter("dni"),request.getParameter("email"),request.getParameter("usuario"),request.getParameter("pass"));
            switch (status){
                case 0:
                    response.sendRedirect("Registro.jsp?status=0");
                   break;
                case 1:
                    response.sendRedirect("index.jsp?status=2");
                   break;
                case 2:
                    response.sendRedirect("Registro.jsp?status=1");
                    break;
                case 3:
                    response.sendRedirect("Registro.jsp?status=2");
                    break;                    
          }
        } finally { 
            out.close();
        }
    } 

    public int BuscarUsuario(String usuario){
        int status = 1;

        String query = "SELECT * FROM usuario WHERE usuario=?";
        ResultSet miRs = null;
        try {
            PreparedStatement miStm = (PreparedStatement) connect.prepareStatement(query);
            miStm.setString(1, usuario);
            miRs = miStm.executeQuery();
            if(miRs.next()) {status = 0;} 
        } catch (SQLException ex) {        }
       return status;
    }
    
    public int BuscarPersona (String DNI){
        int status=1;
        ResultSet miRs = null;
        String myQuery = "Select dni from Usuario where dni=?";
        
        try{
          PreparedStatement miStm = (PreparedStatement) connect.prepareStatement(myQuery); 
          miStm.setString(1, DNI);
          miRs = miStm.executeQuery();
          if (miRs.next()) {status = 0;}
          }catch (SQLException ex){}        
        return status;
    }
    
    public int InsertarUsuario(String apellido, String nombre, String tipo, String dni, String email, String usuario, String pass){
     int status=0;
     
     int pers = BuscarPersona(dni);
     int encontrado = BuscarUsuario(usuario);
        
     if (pers !=0){
      if (encontrado!=0){         
         String myQuery ="Insert into Usuario (apellido,nombre,tipo,dni,email,usuario,clave) values (?,?,?,?,?,?,?)";
         try{
          PreparedStatement miStm = (PreparedStatement) connect.prepareStatement(myQuery);
          miStm.setString (1,apellido);
          miStm.setString(2, nombre);
          miStm.setString(3, tipo);
          miStm.setString(4, dni);
          miStm.setString(5, email);
          miStm.setString(6, usuario);
          miStm.setString(7, pass);
          status = miStm.executeUpdate();
         }catch (SQLException ex){status = 3;}        
     }}else {status=2;}     
     return status;
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
